package com.laf.manage.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.laf.common.constant.MQConstant;
import com.laf.common.utils.mq.RabbitMqHelper;
import com.laf.manage.domain.doc.DynamicDoc;
import com.laf.manage.domain.dto.AddDynamicDocMsg;
import com.laf.manage.domain.po.Dynamic;
import com.laf.manage.mapper.es.DynamicEsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DynamicEsService {

    @Autowired
    private RabbitMqHelper rabbitMqHelper;

    @Autowired
    private DynamicEsMapper dynamicEsMapper;


    /**
     * 发送新增消息
     *
     * @param dto 内容管理id
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW) // 开启新的事务
    public void sendAddDynamicMessage(AddDynamicDocMsg dto) {
        // 新增, 发送消息
        rabbitMqHelper.sendMessage(MQConstant.DYNAMIC_EXCHANGE, MQConstant.DYNAMIC_ADD_ROUTING_KEY, dto);
    }

    /**
     * 修改动态
     *
     * @param dynamic 动态对象
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateDynamicDoc(Dynamic dynamic, List<Long> tagIds) {
        Long dynamicId = dynamic.getId();
        // 查询 es 是否存在动态，如果不存在，发送消息新增即可
        DynamicDoc dynamicDoc = dynamicEsMapper.selectById(dynamicId);
        if (dynamicDoc == null) {
            // 不存在新增 es 数据
            AddDynamicDocMsg addDynamicDocMsg = new AddDynamicDocMsg();
            addDynamicDocMsg.setId(dynamicId);
            addDynamicDocMsg.setTagIds(tagIds);
            sendAddDynamicMessage(addDynamicDocMsg);
        } else {
            DynamicDoc updateDoc = BeanUtil.copyProperties(dynamic, DynamicDoc.class);
            updateDoc.setTagIds(tagIds);
            updateDoc.setVerifyStatus(dynamic.getVerifyStatus().getCode());
            // 存在更新es 数据
            dynamicEsMapper.updateById(updateDoc);
        }
    }

    /**
     * 删除动态
     *
     * @param ids 动态id 集合
     */
    public void sendDeleteDynamicDoc(List<Long> ids) {
        // 删除 es
        rabbitMqHelper.sendMessage(
                MQConstant.DYNAMIC_EXCHANGE,
                MQConstant.DYNAMIC_DELETE_ROUTING_KEY,
                ids
        );
    }


    /**
     * 批量修改 es 中动态的浏览量
     */
    public void batchUpdateHits(List<Dynamic> dynamicList) {
        if (CollUtil.isNotEmpty(dynamicList)){
            List<DynamicDoc> dynamicDocs = BeanUtil.copyToList(dynamicList, DynamicDoc.class);
            dynamicEsMapper.updateBatchByIds(dynamicDocs);
        }

    }

}
